from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAdminUser
from meiduo_admin.serializers.users import LoginModelSerializer, UserModelSerializer
from users.models import User


class AdminLoginView(CreateAPIView):
    serializer_class = LoginModelSerializer
    queryset = User.objects.all()


@method_decorator(permission_required('users.view_user_api', raise_exception=True), name='get')
class UsersView(ListAPIView):
    serializer_class = UserModelSerializer
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        data = self.request.query_params
        keyword = data.get('keyword')
        if keyword:
            queryset = User.objects.filter(is_staff=False, username__contains=keyword)
        else:
            queryset = User.objects.filter(is_staff=False)
        return queryset
